<?php
namespace App\Http\Controllers;
use App\Models\Project;
use Illuminate\Http\Request;
class ProjectController extends CommonController
{
    public function index()
    {
        dump('Project项目维护');
    }
    public function getAll(Request $request)  {
        // 使用示例
        $sortBy = [
            'sort' => 'asc',
            'created_at' => 'desc',
        ];
        $select = ['id', 'name'];
        return getModelAllList(\App\Models\Project::class, $sortBy, ['status' => 1],null,'', $select);
    }
    // 示例方法，用于展示后台首页
    public function getlist(Request $request)
    {
        $page = $request->input('page',1);
        $limit = $request->input('limit',10);
        $status = $request->input('status',null);
        $name = $request->input('name',null);
        $sortBy = $request->input('sortBy', ['created_at' => 'desc','status' => 'desc']);
        $model = new Project();
        $query = $model->query();
        //定义排序查询
        foreach ($sortBy as $field => $direction) {
            $query->orderBy($field, $direction);
        }
        //状态条件
        if($status){
            $query->where('status','=',$status);
        }
        //多个查询
        if($name){
            $query->where('name','like', '%'.$name.'%');
            $query->orWhere('content','like', '%'.$name.'%');
        }
        //分页查询
        $items = $query->paginate( $limit,['*'],'page',$page)->toArray();
        //返回对应格式
        $data = [
            "data"=>$items['data'] ,
            "total"=>$items['total'],
            "limit"=>$items['per_page'],
            "page"=>$items['current_page'],
            "last_page"=>$items['last_page']
        ];
        if($items['total'] == 0){
            return re_warning('暂无数据',null);
        }else{
            return re_success('操作成功',$data);
        }
    }
    public function create(Request $request)
    {
        $info = Project::where('name',$request->input('name'))->exists();
        if($info){
            return  re_warning("项目《{$request->input('name')}》已存在",null);
        }
        return insertData('name',$request->all(), Project::class);
    }
    public function update(Request $request)
    {

        $info = Project::where('name',$request->input('name'))->where('id','<>',$request->input('id'))->exists();
        if($info){
            return  re_warning("项目《{$request->input('name')}》已存在",null);
        }
        return   updateData(Project::class,$request->input('id'),$request->all());
    }
    public function delete(Request $request){
        return deleteData($request,Project::class);
    }
    public function info(Request $request)
    {
        return infoData($request,Project::class);
    }
    public function status(Request $request)
    {
         return toggleModelStatus($request, Project::class);

    }

}
